<?php
namespace Hilaoyu\LaravelExtend\Services\ThirdPartyLogin\Drivers;

use Hilaoyu\Utils\UtilHttp;

/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2017/12/21
 * Time: 14:56
 */
class DriverQq extends AbstractDriver
{

    const API_CODE = 'https://graph.qq.com/oauth2.0/authorize?';
    const API_ACCESS_TOKEN = 'https://graph.qq.com/oauth2.0/token';
    const API_OPENID = 'https://graph.qq.com/oauth2.0/me';
    const API_USER_INFO = 'https://graph.qq.com/user/get_user_info';

    static protected $configs = [];

    protected $AppId = '';
    protected $AppKey = '';
    protected $RedirectUri = '';
    protected $AppType = '';
    protected $DriverName = '';

    public $access_token = '';
    public $openid = '';
    public $unionid = '';


    public function __construct($config)
    {
        $this->AppId = isset($config['app_id']) ? $config['app_id'] : '';
        $this->AppKey = isset($config['app_id']) ? $config['app_key'] : '';
        //$this->RedirectUri = isset($config['app_id']) ? $config['redirect_uri'] : '';
        $this->AppType = isset($config['app_id']) ? $config['type'] : '';
        $this->DriverName = isset($config['driver']) ? $config['driver'] : 'qq';
    }

    public function getDriverName()
    {
        return $this->DriverName;
    }


    public function buildLoginUrl($state=''){
        $url = self::API_CODE;
        $params = [
            'client_id' => $this->AppId,
            'response_type' => 'code',
            'scope' => 'get_user_info',
            'state' => trim($state),
            'redirect_uri' => route('web.l-e-s.third_party_login.return'),
        ];

        return $url . UtilHttp::paramsArrayToStr($params);
    }


    public function getAuthorization($code){
        $params = [
            'client_id' => $this->AppId,
            'client_secret' => $this->AppKey,
            'code' => $code,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $this->RedirectUri,
        ];
        $response = UtilHttp::Request(self::API_ACCESS_TOKEN,$params,'get');

        if (!$response) {
            return false;
        }

        if (strpos($response, "callback") !== false) {

            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
            $msg = json_decode($response);

            if (isset($msg->error)) {
                $this->setError('authorization return error: ' . $msg->error . ':' . $msg->error_description);
            }
        }

        parse_str($response, $access);
        if (empty($access['access_token'])) {
            $this->setError('authorization return access_token was empty');
            return false;
        }
        $this->access_token = $access['access_token'];




        return $access;

    }

    public function getOpenId(array $authorization){
        //get openid
        $params = [
            'access_token'=>$authorization['access_token'],
            'unionid' => '0',
        ];

        $response = UtilHttp::Request(self::API_OPENID,$params,'get');
        if(!$response){
            $this->setError('get openid network error ');
            return false;
        }

        if(strpos($response, "callback") !== false){

            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);
        }

        $user = json_decode($response);

        if(isset($user->error)){
            $this->setError('get openid return error: '. $user->error.':'. $user->error_description);
            return false;
        }

        if(empty($user->openid)){
            $this->setError('get openid return :openid was empty ');
            return false;
        }


        $this->openid = $user->openid;
        $this->unionid = isset($user->unionid) ?  $user->unionid : $user->openid;

        return $this->openid;
    }

    public function getUnionId()
    {
        // TODO: Implement getUnionId() method.

        return $this->unionid;
    }

    public function getUserinfo($openid='',$access_token=''){
        $openid = empty($openid) ? $this->openid : $openid;
        $access_token = empty($access_token) ? $this->access_token : $access_token;

        $params = [
            'access_token'=>$access_token,
            'oauth_consumer_key'=>$this->AppId,
            'openid' => $openid,
        ];
        $response = UtilHttp::RequestJson(self::API_USER_INFO,$params,'get');

        if(!$response){
            return false;
        }
        if($response['ret'] != 0){
            $this->setError('get user_info return error: '. $response['ret'].':'. $response['msg']);
            return false;
        }

        $response['openid'] = $openid;
        if(empty($response['unionid'])){
            $response['unionid'] = $response['openid'];
        }

        $response['headimgurl'] = isset($response['figureurl_qq_2']) ? $response['figureurl_qq_2'] : '';
        return $response;
    }

}
